package com.dys.designpattern.singleton.applicationscenarios;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * @author 田建松
 * @version V1.0.0
 * @description 单例模式用在数据库连接中，保证在整个应用中只有一个数据库连接实例，避免了资源的浪费和不必要的连接开销
 * @date 2024/5/10
 * @since 1.0
 */
public class DatabaseConnection {

    private static DatabaseConnection instance;
    private Connection connection;

    private DatabaseConnection() {
        // 创建数据连接的逻辑，这里假设使用MySQL数据库，连接到名为air的数据库
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            connection = DriverManager.getConnection("jdbc:mysql//localhost:3306/air", "root", "root123");
        } catch (SQLException | ClassNotFoundException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    public static DatabaseConnection getInstance() {
        if (instance == null) {
            instance = new DatabaseConnection();
        }
        return instance;
    }

    public Connection getConnection() {
        return connection;
    }
}
